package com.wt.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wt.admin.config.SecUtils;
import com.wt.admin.entity.WqunAccount;
import com.wt.admin.entity.WqunCommunity;
import com.wt.admin.entity.WqunCommunityBan;
import com.wt.admin.entity.rewentity.RewCommunityUserMess;
import com.wt.admin.service.WqunAdminService;
import com.wt.admin.service.WqunCommunityBanService;
import com.wt.admin.service.WqunCommunityService;
import com.wt.admin.service.impl.WqunAdminServiceImpl;
import com.wt.admin.service.impl.WqunCommunityBanServiceImpl;
import com.wt.admin.service.impl.WqunCommunityServiceImpl;
import com.wt.commonutils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 社区讨论表 前端控制器
 * </p>
 *
 * @author wt
 * @since 2023-09-17
 */
@RestController
@Api(tags = "社区管理")
@CrossOrigin
@RequestMapping("/wqunCommunity")
public class WqunCommunityController {

    @Autowired
    WqunCommunityService wqunCommunityService = new WqunCommunityServiceImpl();

    @Autowired
    WqunAdminService wqunAdminService = new WqunAdminServiceImpl();

    @Autowired
    WqunCommunityBanService wqunCommunityBanService = new WqunCommunityBanServiceImpl();


    //使用一个链队列来保留用户的聊天信息
    LinkedList<WqunCommunity> wqunCommunityLinkedList = new LinkedList<>();

    //返回给用户的信息的链表
    LinkedList<WqunCommunity> resCommunityList = new LinkedList<>();

    //社区信息是否有变动
    boolean wqunCommunityIsChange  = true;



    //社区导论用户信息
    @ApiOperation("社区导论用户信息")
    @GetMapping("/communityUserMess")
    @PreAuthorize("hasAnyAuthority('wqunCommunity:communityUserMess')")
    public R communityUserMess(){
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        queryWrapper.select("id","nick_name","user_type","avatar");
        List<WqunAccount> findAllAccountPublic = wqunAdminService.list(queryWrapper);
        List<RewCommunityUserMess> communityUserMess = new ArrayList<>();
        for (int i = 0; i < findAllAccountPublic.size(); i++) {

            WqunAccount wqunAccount = findAllAccountPublic.get(i);
            RewCommunityUserMess rewCommunityUserMess  =new RewCommunityUserMess();
            //用户基本信息
            rewCommunityUserMess.setId(wqunAccount.getId());
            rewCommunityUserMess.setNickName(wqunAccount.getNickName());
            rewCommunityUserMess.setUserType(wqunAccount.getUserType());
            rewCommunityUserMess.setAvatar(wqunAccount.getAvatar());
            //讨论次数
            QueryWrapper<WqunCommunity> speakNumQW = new QueryWrapper<>();
            speakNumQW.eq("uid",rewCommunityUserMess.getId());
            int speakNum = wqunCommunityService.count(speakNumQW);
            rewCommunityUserMess.setSpeakNum(speakNum);

            //是否被禁言
            QueryWrapper<WqunCommunityBan> isBanQW = new QueryWrapper<>();
            isBanQW.eq("is_ban",1);
            isBanQW.eq("uid",rewCommunityUserMess.getId());
            int count = wqunCommunityBanService.count(isBanQW);
            rewCommunityUserMess.setBan(count>=1);
            communityUserMess.add(rewCommunityUserMess);
        }

        return R.ok().data("communityUserMess",communityUserMess);
    }



    //查询指定id社区信息
    @ApiOperation("查询指定id社区信息")
    @GetMapping("/getCommunityById/{id}")
    public R getCommunityById(@PathVariable("id") String id){
        WqunCommunity getCommunityById = wqunCommunityService.getById(id);
        if(getCommunityById != null){
            return R.ok().message("查询成功").data("getCommunityById",getCommunityById);
        }else{
            return R.error().message("查询失败");
        }
    }

    //第一请求查询所有社区信息
    @ApiOperation("第一请求查询所有社区信息")
    @GetMapping("/findAllCommunityFirst/{total}")
    @PreAuthorize("hasAnyAuthority('wqunCommunity:findAllCommunityFirst')")
    public R findAllCommunityFirst(@PathVariable("total") int total){
        findAllComment();
        int listEndIndex = wqunCommunityLinkedList.size()-1;
        resCommunityList.clear();//将用户评论信息清空
        for (int i = 0; i < total; i++) {
            resCommunityList.addFirst(wqunCommunityLinkedList.get(listEndIndex-i));
        }
        return R.ok().data("findAllCommunity",resCommunityList);
    }

    //查询所有社区信息
    @ApiOperation("查询所有社区信息")
    @GetMapping("/findAllCommunity/{startId}/{total}")
    @PreAuthorize("hasAnyAuthority('wqunCommunity:findAllCommunity')")
    public R findAllCommunity(@PathVariable("startId")String startId,@PathVariable("total") int  total){


        int listEndIndex = wqunCommunityLinkedList.size()-1;
        resCommunityList.clear();//将用户评论信息清空
        for (int i = 0; i < total; i++) {
            if(wqunCommunityLinkedList.size() == 0){
                break;
            }
            WqunCommunity wqunCommunity = wqunCommunityLinkedList.get(listEndIndex - i);
            if(!Objects.equals(wqunCommunity.getId(), startId)){
                resCommunityList.addFirst(wqunCommunity);
            }else{
                break;
            }
        }
        return R.ok().data("findAllCommunity",resCommunityList);
    }

    public void findAllComment(){
        QueryWrapper<WqunCommunity> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        queryWrapper.last("limit 0,50");
        List<WqunCommunity> findAllCommunity = wqunCommunityService.list(queryWrapper);
        wqunCommunityLinkedList.clear();
        for (int i = 0; i < findAllCommunity.size(); i++) {
            wqunCommunityLinkedList.addFirst(findAllCommunity.get(i));
        }
    }

    //添加文本信息
    @ApiOperation("添加文本信息")
    @PostMapping("/addCommunity")
    @PreAuthorize("hasAnyAuthority('wqunCommunity:addCommunity')")
    public R addCommunity(@RequestBody WqunCommunity wqunCommunity){
        //判断是否被禁言
        QueryWrapper<WqunCommunityBan> isBanQW  =new QueryWrapper<>();
        isBanQW.eq("uid",wqunCommunity.getUid());
        isBanQW.eq("is_ban",1);
        int banCount = wqunCommunityBanService.count(isBanQW);
        if(banCount>=1){
            return R.error().message("你已被禁言，请联系管理员解除");
        }
        boolean saveRes = wqunCommunityService.save(wqunCommunity);
        QueryWrapper<WqunCommunity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("uid",wqunCommunity.getUid());
        queryWrapper.last("limit 1");
        WqunCommunity wqunCommunityById = wqunCommunityService.getOne(queryWrapper);
        if(wqunCommunityLinkedList.size() >= 50){
            wqunCommunityLinkedList.removeFirst();
            wqunCommunityLinkedList.addLast(wqunCommunityById);
        }else{
            wqunCommunityLinkedList.addLast(wqunCommunityById);
        }
        if(saveRes){
            return R.ok();
        }else{
            return R.error().message("发送失败");
        }
    }


    //删除指定id社区信息
    @ApiOperation("删除指定id社区信息")
    @GetMapping("/deleteCommunityById/{id}/{uid}")//信息id以及用户id
    @PreAuthorize("hasAnyAuthority('wqunCommunity:deleteCommunityById')")
    public R deleteCommunityById(@PathVariable("id") String id,@PathVariable("uid") String uid){
        //获取用户信息
        String userUid = SecUtils.getUserMess().getId();
        String userType = SecUtils.getUserMess().getUserType();
        if(!userUid.equals(uid) && userType.equals("0")){//普通用户并且想要删除别人的信息
            return R.error().message("非法请求");
        }
        WqunCommunity byId = wqunCommunityService.getById(id);
        if(!userUid.equals(uid) && userType.equals("1")){//是管理员，删除别人的信息
            byId.setType("-2");
        }else{//是管理员，删除自己的信息
            byId.setType("-1");
        }
        boolean deleteRes = wqunCommunityService.updateById(byId);
        if(deleteRes){
            for (int i = 0; i < wqunCommunityLinkedList.size(); i++) {//删除后修改该数据
                if(wqunCommunityLinkedList.get(i).getId().equals(id)){
                    WqunCommunity wqunCommunity = wqunCommunityLinkedList.get(i);
                    wqunCommunity.setType("-1");
                    wqunCommunityLinkedList.set(i,wqunCommunity);
                }
            }
            return R.ok().message("撤回成功");
        }else{
            return R.error().message("撤回失败");
        }
    }

    //管理员删除指定id社区信息
//    @ApiOperation("删除指定id社区信息")
//    @GetMapping("/admin/deleteCommunityById/{id}")
//    public R adminDeleteCommunityById(@PathVariable("id") String id){
//        WqunCommunity byId = wqunCommunityService.getById(id);
//        byId.setType("-2");
//        boolean deleteRes = wqunCommunityService.updateById(byId);
//        if(deleteRes){
//            for (int i = 0; i < wqunCommunityLinkedList.size(); i++) {//删除后修改该数据
//                if(wqunCommunityLinkedList.get(i).getId().equals(id)){
//                    WqunCommunity wqunCommunity = wqunCommunityLinkedList.get(i);
//                    wqunCommunity.setType("-2");
//                    wqunCommunityLinkedList.set(i,wqunCommunity);
//                }
//            }
//            return R.ok().message("撤回成功");
//        }else{
//            return R.error().message("撤回失败");
//        }
//    }
}

